# 停止防火墙
systemctl stop firewalld
# 禁止防火墙开机启动
systemctl disable firewalld
# 临时关闭swap分区
swapoff -a
# 永久关闭swap分区
sed -i 's/\(.*swap.*\)/#&/' /etc/fstab

# 临时启用内核模块--桥接防火墙
modprobe br_netfilter

# 临时开启路由转发功能
echo 1 >  /proc/sys/net/ipv4/ip_forward
echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables

# 设置开机启动桥接防火墙
echo "modprobe br_netfilter" >> /etc/rc.d/rc.local
# 给文件设置可执行权限, 否则开机启动后
chmod +x /etc/rc.d/rc.local

# 设置开机启用路由转发功能
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf

# 添加docker的yum仓库源
cat docker-ce.repo > /etc/yum.repos.d/docker-ce.repo

# 修改yum源为中科大
sed -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org|baseurl=https://mirrors.ustc.edu.cn|g' -i.bak /etc/yum.repos.d/CentOS-*.repo

# 添加k8s的yum仓库源
cat k8s.repo > /etc/yum.repos.d/kubernetes.repo

yum makecache

# 更新系统时间
yum install -y ntpdate 
ntpdate asia.pool.ntp.org
date

# 安装k8s及containerd包, 注意这里版本号, 如果修改了版本号记得替换下面pause:3.8的版本为匹配版本
yum install -y kubeadm-1.25.0-0 kubelet-1.25.0-0 kubectl-1.25.0-0
yum install -y ./containerd.io-1.6.6-3.1.el7.x86_64.rpm

# 创建默认的containerd配置文件
mv /etc/containerd/config.toml /etc/containerd/config.toml.back
containerd config default > /etc/containerd/config.toml
sed -ri '/sand/ s/sandbox_image = (.*)/sandbox_image = "registry.cn-hangzhou.aliyuncs.com\/google_containers\/pause:3.8"/' /etc/containerd/config.toml


systemctl daemon-reload
systemctl enable containerd
systemctl start containerd
systemctl enable kubelet
systemctl start kubelet

# 创建crictl配置文件
crictl config --set runtime-endpoint="unix:///run/containerd/containerd.sock"
crictl config --set timeout=20

# 重启containerd
systemctl restart containerd

read -p "当前主机是master节点吗(y/n)" is_master
if [[ $is_master == "y" ]]; then
	echo "Init Kube Cluster Master Node"
else
  echo "The child node is ready. Manually run the join command to join the cluster"
	exit
fi



# 初始化k8s应用 
kubeadm init --v=5 --image-repository registry.cn-hangzhou.aliyuncs.com/google_containers --pod-network-cidr=10.244.0.0/16 --control-plane-endpoint=192.168.21.119:6443

mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
export KUBECONFIG=/etc/kubernetes/admin.conf

# 安装网络支持插件
kubectl apply -f kube-flannel.yml
systemctl restart kubelet

echo "Master Node Init Completed"
